﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace LaunchPad.Core
{
    public class TimeSpanConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string result = string.Empty;
            if (value is TimeSpan)
            {
                var timeSpan = (TimeSpan) value;
                if (parameter == null || !(parameter is string))
                {
                    result = string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}.{4:D1}",
                                           timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds,
                                           (int) Math.Round(timeSpan.Milliseconds/100.0));
                }
                else
                {
                    DateTime time = DateTime.Today;
                    time = time.Add(timeSpan);
                    result = time.ToString((string)parameter);
                }
            }
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            /* I've given up stuggling with the crappy TimeSpan and DateTime parsing methods */

            double hours = 0;
            double minutes = 0;
            double seconds = 0;

            var parts = ((string) value).Split(':');

            switch(parts.Length)
            {
                case 1:
                    /* Assume seconds */
                    double.TryParse(parts[0], out seconds);
                    break;
                case 2:
                    double.TryParse(parts[0], out minutes);
                    double.TryParse(parts[1], out seconds);
                    break;
                case 3:
                    double.TryParse(parts[0], out hours);
                    double.TryParse(parts[1], out minutes);
                    double.TryParse(parts[2], out seconds);
                    break;
            }

            TimeSpan hourSpan = TimeSpan.FromHours(hours);
            TimeSpan minuteSpan = TimeSpan.FromMinutes(minutes);
            TimeSpan secondSpan = TimeSpan.FromSeconds(seconds);

            return hourSpan + minuteSpan + secondSpan;
        }

        #endregion
    }
}